package net.code4life;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import net.code4life.core.webserver.JettyServerWapper;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Application {
	private static Log logger = LogFactory.getLog(Application.class);
	private static final String DEFAULT_WEBAPP_PATH = "src/main/webapp";

	private String rootDir;

	private static JettyServerWapper webserver;

	private static void onInit() {
		InputStream ins = null;
		Properties props = null;
		try {
			ins = ClassLoader.getSystemResourceAsStream("jetty.properties");
			props = new Properties();
			props.load(ins);

			String webappPath = props.getProperty("server.webapppath",
					DEFAULT_WEBAPP_PATH);
			int port = Integer.parseInt(props
					.getProperty("server.port", "80"));
			String rootDir = props.getProperty("server.rootDir", "ROOT");
			webserver = new JettyServerWapper(port, webappPath, rootDir);
		} catch (IOException e) {
			logger.error("读取Jetty Server配置文件失败", e);
		} finally {
			IOUtils.closeQuietly(ins);
		}
	}

	public static void startWebServer() {
		if (webserver == null) {
			onInit();
		}
		try {
			webserver.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void stopWebServer() {
		if (webserver != null) {
			try {
				webserver.stop();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		startWebServer();
	}
}
